package com.jy.modules.cims.interact.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleBeanUtils;
import com.jy.modules.cims.data.dao.CreditRightDao;
import com.jy.modules.cims.data.dto.ConfirmParamDto;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditDetailQueryDto;
import com.jy.modules.cims.data.dto.QuotaDetailUnlockParamDto;
import com.jy.modules.cims.data.dto.ConfirmParamDto.CreditRightInfo;
import com.jy.modules.cims.data.dto.credit.RedeemParamDto;

/**
 * @description 过滤债权工具类。
 * @author shengzhoutao
 * @date 2015-05-23
 */
@Service("com.jy.modules.cims.interact.util.FilterCreditDetailUtil")
public class FilterCreditDetailUtil {
	private static final Logger logger = LoggerFactory.getLogger(FilterCreditDetailUtil.class);
	private static final int DEFAULT_PAGE_SIZE = 500;
	
	@Autowired
	private CreditRightDao creditRightDao;

	/**
	 * @description 根据不同参数对象过滤债权明细
	 * @author shengzhoutao
	 * @param obj
	 *            参数对象
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws NoSuchFieldException
	 */
	public void filterCreditDetail(Object obj) {
		// 是否过滤债权(true:过滤; false:不过滤)
		if (!CimsConstant.FILTER_CREDIT_DETAIL) {
			return;
		}

		String propertyName = "transferId";
		try {
			// 额度明细释放
			if (obj instanceof QuotaDetailUnlockParamDto) {
				QuotaDetailUnlockParamDto result = (QuotaDetailUnlockParamDto) obj;
				List<QuotaDetailUnlockParamDto.CreditRightUnlockInfo> list = result.getCreditRightUnlockList();
				if (CollectionsUtils.isEmpty(list)) {
					return;
				}
				// transferId
				result.setCreditRightUnlockList(intersection(list, getCreditDetail(list, propertyName, result.getSource()), propertyName));
				obj = result;
			}
			// 转让结果确认
			else if (obj instanceof ConfirmParamDto) {
				ConfirmParamDto result = (ConfirmParamDto) obj;
				List<CreditRightInfo> list = result.getCreditRightList();
				if (CollectionsUtils.isEmpty(list)) {
					return;
				}
				// transferId
				result.setCreditRightList(intersection(list, getCreditDetail(list, propertyName, null), propertyName));
				obj = result;
			}
			// 批量赎回
			else if (obj instanceof RedeemParamDto) {
				RedeemParamDto result = (RedeemParamDto) obj;
				List<CreditDetailDto> list = result.getCreditDetailList();
				if (CollectionsUtils.isEmpty(list)) {
					return;
				}
				// transferId
				result.setCreditDetailList(intersection(list, getCreditDetail(list, propertyName, null), propertyName));
				obj = result;
			}
		} catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			logger.error("过滤债权异常:", e);
		}
	}

	/**
	 * @description 获取符合条件的债权明细
	 * @author shengzhoutao
	 * @param collection
	 *            包含债权转让编号的对象的集合
	 * @param propertyName
	 *            要提取的转让编号属性名
	 * @return List<CreditDetailDto> 债权明细
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private List<CreditDetailDto> getCreditDetail(List collection, String propertyName, String source) throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		if (CollectionsUtils.isEmpty(collection)) {
			return null;
		}

		List<String> transferIdList = CollectionsUtils.extractToList(collection, propertyName);
		if (CollectionsUtils.isEmpty(transferIdList)) {
			return null;
		}

		// select ... from .. where in (...)
		// SQL语句中in()的集合元素个数限制不能超过1000，所以DEFAULT_PAGE_SIZE分页查询

		int totalCount = transferIdList.size();
		int pageSum = totalCount / DEFAULT_PAGE_SIZE;
		pageSum = (totalCount % DEFAULT_PAGE_SIZE == 0) ? pageSum : pageSum + 1;

		List<CreditDetailDto> newList = new ArrayList();
		List<String> queryList = null;
		for (int page = 1; page <= pageSum; page++) {
			queryList = new ArrayList();
			int start = (page - 1) * DEFAULT_PAGE_SIZE;
			int end = page * DEFAULT_PAGE_SIZE;
			end = (end > totalCount) ? totalCount : end;

			for (int index = start; index < end; index++) {
				queryList.add(transferIdList.get(index));
			}

			List<CreditDetailDto> list = getCreditDetailByUnequalCoreCreditStatus(queryList, source);

			if (CollectionsUtils.isNotEmpty(list)) {
				// 返回a+b的新List
				newList = CollectionsUtils.union(newList, list);
			}
		}
		logger.info("数据库查询符合条件的债权个数：" + newList.size());
		return newList;
	}

	/**
	 * @description 查询核心系统不是(提前结清:95;信用贷--债权重组:88;抵押贷--展期结清:89)的债权
	 * @author shengzhoutao
	 * @param transferIdList
	 *            债权转让编号集合
	 * @return List<CreditDetailDto>
	 */
	private List<CreditDetailDto> getCreditDetailByUnequalCoreCreditStatus(List<String> transferIdList, String source) {
		CreditDetailQueryDto creditDetailQueryDto = new CreditDetailQueryDto();
		creditDetailQueryDto.setTransferIdList(transferIdList);
		//creditDetailQueryDto.setCreditorStatus(CimsConstant.CORE_CREDIT_STATUS_SETTLE_AHEAD);
		if (CimsConstant.QUOTA_UNLOCK_SOURCE.equals(source)) {
			return getQuotaCreditDetailByUnequalCoreCreditStatus(creditDetailQueryDto);
		} else {
			return getCreditDetailByUnequalCoreCreditStatus(creditDetailQueryDto);
		}
	}

	/**
	 * @description 查询债权
	 * @author shengzhoutao
	 * @param creditDetailQueryDto
	 *            查询债权对象
	 * @return List<CreditDetailDto>
	 */
	private List<CreditDetailDto> getCreditDetailByUnequalCoreCreditStatus(CreditDetailQueryDto creditDetailQueryDto) {
		return creditRightDao.getCreditDetailByUnequalCoreCreditStatus(SearchParamUtil.getSearchParam(creditDetailQueryDto));
	}

	/**
	 * @description 查询债权
	 * @author shengzhoutao
	 * @param creditDetailQueryDto
	 *            查询债权对象
	 * @return List<CreditDetailDto>
	 */
	private List<CreditDetailDto> getQuotaCreditDetailByUnequalCoreCreditStatus(CreditDetailQueryDto creditDetailQueryDto) {
		return creditRightDao.getQuotaCreditDetailByUnequalCoreCreditStatus(SearchParamUtil.getSearchParam(creditDetailQueryDto));
	}

	/**
	 * @description 提取集合a包含集合b的新集合，集合的对象以字段属性的值相同为基准。
	 * @author shengzhoutao
	 * @param a
	 *            集合a
	 * @param b
	 *            集合b
	 * @param fieldName
	 *            字段属性
	 * @return List<T1>
	 * @throws NoSuchFieldException
	 */
	private <T1, T2> List<T1> intersection(List<T1> a, List<T2> b, String fieldName) throws NoSuchFieldException {
		List<T1> newList = new ArrayList<T1>();

		if (CollectionsUtils.isEmpty(a) || CollectionsUtils.isEmpty(b)) {
			logger.info("债权个数为空！");
			return null;
		}
		logger.info("===>>过滤前债权个数：" + a.size());
		for (T1 elementA : a) {
			Object fieldValueForA = SimpleBeanUtils.getFieldValue(elementA, fieldName);
			for (T2 elementB : b) {
				Object fieldValueForB = SimpleBeanUtils.getFieldValue(elementB, fieldName);
				if (fieldValueForA.toString().trim().equals(fieldValueForB.toString().trim())) {
					newList.add(elementA);
				}
			}
		}
		logger.info("===>>过滤后债权个数：" + newList.size());
		return newList;
	}

}
